<template>
  <el-dialog :visible.sync="dialogVisible" width="60%" :before-close="beforeClose" :title="dialogTitle">
    <el-form
        :rules="rules"
        :model="formData"
        ref="formData"
        label-width="120px"
    >
      <el-row :gutter="2">
        <el-col :span="12">
          <el-form-item label="机构" prop="whjg">
            <el-select v-model="formData.whjg" filterable
                       placeholder="请选择机构" style="width: 100%" clearable @change="handWhjgChange">
              <el-option :label="option.deptName" :value="option.deptCode" v-for="(option, oi) in framedepartmentList"
                         :key="oi"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="接口开票开票人" prop="jkkpkpr">
            <el-select v-model="formData.jkkpkpr" style="width: 100%" :disabled="flag" :placeholder=placeText>
              <el-option :value="item.name" :label="item.name" v-for="(item,index) in kprList" :key="index">
                {{ item.name }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="2">
        <el-col :span="12">
          <el-form-item label="区域代码" prop="qydm">
            <dict-select v-model="formData.qydm" showCode :dict-code="DictCode.VMS_QYDM"
                         @change="changeQydm" style="width: 100%"></dict-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用单位编号" prop="sydwbh">
            <el-input v-model="formData.sydwbh" placeholder="请输入使用单位编号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="2">
        <el-col :span="12">
          <el-form-item label="文件生成状态" prop="bswjsczt">
            <el-select v-model="formData.bswjsczt" style="width: 100%">
              <el-option value="Y" label="启用">启用</el-option>
              <el-option value="N" label="关闭">关闭</el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开具发票状态" prop="fpkjzt">
            <el-select v-model="formData.fpkjzt" style="width: 100%">
              <el-option value="Y" label="启用">启用</el-option>
              <el-option value="N" label="关闭">关闭</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="2">
        <el-col :span="12">
          <el-form-item label="纳税人识别号" prop="nsrsbh">
            <el-input v-model="formData.nsrsbh" placeholder="请输入纳税人识别号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纳税人名称" prop="nsrmc">
            <el-input v-model="formData.nsrmc" placeholder="请输入纳税人名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="监制章图片">
          <el-upload
              class="upload-component"
              ref="upload"
              :auto-upload="false"
              :file-list="fileList"
              :on-change="onChange"
              :on-remove="onRemove"
              :limit="1"
              action=""
              multiple
              drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text" v-if="formData.bswjid">上传图片覆盖原有监制章图片</div>
            <div class="el-upload__text" v-else>请上传 PNG文件</div>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
      </el-row>
    </el-form>
    <el-row style="margin-top: 10px">
      <div class="centered-dialog">
        <el-button type="primary" size="mini" @click="confirmSubmit" :loading="loading">
          {{ this.loading ? '正在上传， 请不要关闭' : '确认' }}
        </el-button>
        <el-button type="primary" size="mini" @click="beforeClose">
          取消
        </el-button>
      </div>
    </el-row>
  </el-dialog>
</template>

<script>
import DictSelect from "@/views/invoiceTemplate/components/DictSelect/DictSelect.vue";
import {DictCode} from "@/utils/DictConstant";
import {getDetail, getFramedepartment, getJkkprByWhjg, uploadAction} from "@/api/invoiceTemplate";
import { splitArrs } from '@/utils/splitArr.js'

export default {
  computed: {
    DictCode() {
      return DictCode
    }
  },
  components: {DictSelect},
  watch: {
    'formData.whjg'() {
      if (this.formData.whjg == '') {
        this.flag = true
        this.placeText = '请先选择机构'
        this.formData.jkkpkpr = ''
      } else {
        this.flag = false
        this.placeText = '请选择接口开票人'
        this.getKpr()
      }
    }
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    dialogTitle: {
      type: String,
      default: '数电发票启用及版式新增'
    }
  },
  data() {
    return {
      dialogVisible: false,
      data: {},
      fileList: [],
      loading: false,
      formData: {
        whjg: "",
        qydm: "",
        qymc: "",
        sydwbh: "",
        bswjsczt: "",
        fpkjzt: "",
        bswjid: "",
        nsrsbh: "",
        nsrmc: "",
        jkkpkpr: ""
      },
      framedepartmentList: [],
      row: {},
      flag: true,
      placeText: '请先选择机构',
      kprList: [],
      rules: {
        whjg: [
          {required: true, message: '请选择所在机构', trigger: 'change'}
        ],
        jkkpkpr: [
          {required: true, message: '请选择接口开票开票人', trigger: 'change'}
        ],
        qydm: [
          {required: true, message: '请选择区域代码', trigger: 'change'}
        ],
        sydwbh: [
          {required: true, message: '请输入使用单位编号', trigger: 'change'}
        ],
        bswjsczt: [
          {required: true, message: '请选择版式文件生成状态', trigger: 'change'}
        ],
        fpkjzt: [
          {required: true, message: '请选择发票开具状态', trigger: 'change'}
        ],
        nsrsbh: [
          {required: true, message: '请输入纳税人识别号', trigger: 'change'}
        ],
        nsrmc: [
          {required: true, message: '请输入纳税人名称', trigger: 'change'}
        ]
      }
    };
  },
  mounted() {
    this.getFramedepartment();
  },
  methods: {
    async getDetail() {
      const {data, msg, code} = await getDetail(this.row.bswjid);
      if (code == 200) {
        this.formData = data;
        this.$set(this.formData, 'nsrmc', data.nsztName);
      } else {
        this.$message.error("未查询到数据");
      }
    },
    beforeClose(done) {
      this.formData = {
        whjg: "",
        qydm: "",
        qymc: "",
        sydwbh: "",
        bswjsczt: "",
        fpkjzt: "",
        bswjid: "",
        nsrsbh: "",
        nsrmc: "",
        jkkpkpr: ""
      }
      this.clearFile()
      this.$emit('update:dialogVisible', false);
      done();
    },
    async getKpr() {
      const {code, data, msg} = await getJkkprByWhjg(this.formData.whjg);
      if (code == 200) {
        this.kprList = data;
      }
    },
    onChange(file, fileList) {
      if (fileList.length > 1) {
        this.$message.error(`只能上传一个监制章图片！`)
        return
      }

      let validSuffix = ['png']
      let splits = file.name.split('.')
      let suffix = splits[splits.length - 1]

      if (!validSuffix.includes(suffix)) {
        this.$message.error(`只能上传 ${validSuffix.join(',')} 类型的文件！`)
        this.fileList = fileList.filter(item => item.uid !== file.uid)
        return
      }
      this.fileList = fileList
    },

    onRemove(file, fileList) {
      this.fileList = fileList.filter(item => item.uid !== file.uid)
    },

    clearFile() {
      this.fileList = []
    },

    async confirmSubmit() {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          //判断是否有文件再上传
          if (this.fileList.length === 0 && this.formData.bswjid === "") {
            return this.$message.warning('请选取文件后再上传')
          }
          // 创建 formData 对象
          const formData = new FormData()
          this.fileList.forEach((file) => {
            formData.append('file', file.raw)
          })
          formData.append('whjg', this.formData.whjg)
          formData.append('qydm', this.formData.qydm)
          formData.append('qymc', this.formData.qymc)
          formData.append('sydwbh', this.formData.sydwbh)
          formData.append('bswjsczt', this.formData.bswjsczt)
          formData.append('fpkjzt', this.formData.fpkjzt)
          formData.append('bswjId', this.formData.bswjid)
          formData.append('nsrsbh', this.formData.nsrsbh)
          formData.append('nsrmc', this.formData.nsrmc)
          formData.append('jkkpkpr', this.formData.jkkpkpr)
          this.loading = true
          let {data, code, message} = await uploadAction(formData)
          if (code == 200) {
            this.$parent.getList();
            this.clearFile();
            this.formData = {
              whjg: "",
              qydm: "",
              qymc: "",
              sydwbh: "",
              bswjsczt: "",
              fpkjzt: "",
              nsrsbh: "",
              nsrmc: ""
            }
            this.loading = false
            this.beforeClose();
          }
          this.loading = false
        } else {
          return false
        }
      })
    },
    async getFramedepartment() {
      let {data, code, message} = await getFramedepartment({});
      if (code == 200) {
        // splitArrs(this.framedepartmentList,data,50)
        this.framedepartmentList = data
      }
    },

    changeQydm(value, label) {
      this.formData.qymc = label;
    },
    handWhjgChange(){
      this.formData.jkkpkpr = ''
      this.getFramedepartment();
    }
  },
};
</script>

<style scoped>
.centered-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}


.el-select {

  /deep/ .el-input {
    .el-input--suffix {
      width: 100%;
    }
  }
}
</style>